package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.RedisConstant;
import com.sky.mapper.user.UserDishFlavorMapper;
import com.sky.mapper.user.UserDishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.service.user.UserDishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Slf4j
public class UserDishServiceImpl implements UserDishService {
    @Autowired
    private UserDishMapper userDishMapper;
    @Autowired
    private UserDishFlavorMapper userDishFlavorMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<DishVO> findListByCategory(Long categoryId) {
        String key = RedisConstant.DISH_CACHE_PREFIX+categoryId;
        String cacheDish = (String) redisTemplate.opsForValue().get(key);
        if (StringUtils.hasText(cacheDish)){
            return JSONObject.parseArray(cacheDish, DishVO.class);
        }

        List<DishVO> list = userDishMapper.findListByCategory(categoryId);
        for (DishVO dishVO : list) {
            List<DishFlavor> flavorList = userDishFlavorMapper.findFlavor(dishVO.getId());
            dishVO.setFlavors(flavorList);
        }
        redisTemplate.opsForValue().set(key,JSON.toJSONString(list));
        log.info(list.toString());
        return list;
    }
}
